#include "qpointchooser.h"
#include <QtGui/QPainter>
#include <QtGui/QPen>
#include <QtCore/qmath.h>

QPointChooser::QPointChooser(QWidget *parent) :
    QWidget(parent)
{
    xClick = yClick = 0;
}

int QPointChooser::bHeight() const
{
    return maxH;
}

int QPointChooser::bWidth() const
{
    return maxW;
}

void QPointChooser::setBHeight(int h)
{
    maxH = h; calculate();
}

void QPointChooser::setBWidth(int w)
{
    maxW = w; calculate();
}

void QPointChooser::paintEvent(QPaintEvent *e)
{
    QPainter p(this);
    p.setPen(QPen(Qt::black, 3.0));
    p.drawPoint(xClick, yClick);
    p.setPen(QPen(Qt::gray, 0.5));
    p.drawRect(0, 0, width() - 1, height() - 1);
}

void QPointChooser::mousePressEvent(QMouseEvent *e)
{
    perform(e);
}

void QPointChooser::mouseMoveEvent(QMouseEvent *e)
{
    perform(e);
}

void QPointChooser::perform(QMouseEvent *e)
{
    xClick = qMax(0, qMin(e->x(), width()));
    yClick = qMax(0, qMin(e->y(), height()));
    update();
    calculate();
}

void QPointChooser::calculate()
{
    float w(xClick * maxW);
    float h(yClick * maxH);
    w /= float(width());
    h /= float(height());
    emit pointChoosed(w, h);
    updateGeometry();
}

QSize QPointChooser::sizeHint() const
{
    const int base = 150;
    const float ar = float(maxW) / float(maxH);
    int other;
    if(ar < 1.0f)
    {
        // maxW / maxH < 1.0f
        // maxH > maxW then maxH = base
        // and ar = other / base
        other = qRound(ar * base);
        return QSize(other, base);
    }
    else if(ar > 1.0f)
    {
        // maxH < maxW then maxW = base
        // and ar = base / other
        other = qRound(base / ar);
        return QSize(base, other);
    }
    else return QSize(base, base);
}
